package com.gzzyy.unionchain

import android.app.Application
import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import com.gzzyy.unionchain.communicate.CommunicateService
import com.gzzyy.unionchain.data.ObjectBox
import com.gzzyy.unionchain.data.SaveDataService
import com.gzzyy.unionchain.data.bean.TripleKey
import com.gzzyy.unionchain.data.bean.User
import com.gzzyy.unionchain.util.KeyUtil.getTripleKey
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.webrtc.PeerConnectionFactory

class App : Application() {

    companion object {
        var user: User? = null
        var tripleKey: TripleKey? = null
    }

    private var communicateService: CommunicateService? = null
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            communicateService = null
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val localBinder = service as CommunicateService.LocalBinder?
            communicateService = localBinder?.getService()
        }
    }

    private var saveDataService: SaveDataService? = null
    private val saveDataConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            saveDataService = null
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val localBinder = service as SaveDataService.LocalBinder?
            saveDataService = localBinder?.getService()
        }
    }

    override fun onCreate() {
        super.onCreate()
        ObjectBox.init(this)
        GlobalScope.launch {
            val userBox = ObjectBox.boxStore.boxFor(
                User::class.java
            )
            user = userBox.query().build().findFirst()
            if (user != null) {
                tripleKey = getTripleKey(user?.walletAddress)
            }
        }
        PeerConnectionFactory.initialize(
            PeerConnectionFactory.InitializationOptions
                .builder(this)
                .createInitializationOptions()
        )
        bindService(
            Intent(this@App, CommunicateService::class.java),
            serviceConnection,
            Service.BIND_AUTO_CREATE
        )

        bindService(
            Intent(this@App, SaveDataService::class.java),
            saveDataConnection,
            Service.BIND_AUTO_CREATE
        )
    }
}